package com.javatest.demo.dao;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.javatest.demo.entities.Student;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020-06-28 下午1:31
 */
@DS("mysql")
@Repository
public class StudentDao2 {
    private static final Logger LOGGER = LoggerFactory.getLogger(StudentDao.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void initDb() {
        String sql = "CREATE TABLE if not exists student(id INTEGER PRIMARY KEY  auto_increment, name varchar(30), age int, school varchar(30))";
        jdbcTemplate.update(sql);
    }

    public int insert(Student student) {
        String sql = "insert into student(name, age, school) values (?, ?, ?)";
        List<Object> params = new ArrayList<>();
        params.add(student.getName());
        params.add(student.getAge());
        params.add(student.getSchool());
        return jdbcTemplate.update(sql, params.toArray());
    }

    public List<Student> queryAllStudent() {
        String sql = "select id, name, age, school from student";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
    }
}
